package com.ray.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.http.HttpServletResponse;

public class ResponseUtil {
	public static boolean ERROE=false;
	public static String ERROR_INFO_KEY="info";
	public static boolean OK=true;
	public static String RESULT_KEY="result";
	public static String DATA_KEY="data";
	private ResponseUtil() {
		// TODO Auto-generated constructor stub
	}
	public static HashMap ResponseResult(Object data){
		HashMap result=new HashMap<String, Object>();
		result.put(RESULT_KEY, OK);
		result.put(DATA_KEY, data);
		return result;
	}
	public static HashMap ResponseError(String info){
		HashMap result=new HashMap<String, Object>();
		result.put(RESULT_KEY, ERROE);
		result.put(ERROR_INFO_KEY, info);
		return result;
	}
	
	public final static void downloadfile(HttpServletResponse response, File file, String outfileName, Boolean delete)
			throws IOException {
		FileInputStream f = new FileInputStream(file);
		byte[] fb = new byte[f.available()];
		f.read(fb);
		response.setHeader("Content-disposition",
				"attachment; filename=" + new String(outfileName.getBytes("UTF-8"), "iso8859-1"));
		ByteArrayInputStream bais = new ByteArrayInputStream(fb);
		int b;
		while ((b = bais.read()) != -1) {
			response.getOutputStream().write(b);
		}
		response.getOutputStream().flush();
		f.close();
		if (delete) {
			file.delete();
		}
	}
	
	public static void ResponseData(HttpServletResponse response,String data){
		if(null!=data){
			try {
				//response.setContentType("application/xml;utf-8");
				response.setCharacterEncoding("utf-8");
				PrintWriter pw=response.getWriter();
				pw.write(data);
				pw.flush();
				pw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}
